package org.example.demo;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.example.demo.controller.DatasourceController;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

@SpringBootApplication
@Slf4j
public class SimplestDemoApplication implements ApplicationContextAware, ApplicationRunner {

    private ApplicationContext applicationContext;

    public static void main(String[] args) {
        SpringApplication.run(SimplestDemoApplication.class, args);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 这是用默认数据源做测试
        DynamicDataSourceProperties dynamicDataSourceProperties = applicationContext.getBean(DynamicDataSourceProperties.class);
        MetaObject metaObject = SystemMetaObject.forObject(applicationContext.getBean(DatasourceController.class));
        Map<String, Connection> connectionMap = (Map<String, Connection>) metaObject.getValue("datasourceServiceMap");
        try {
            for (Map.Entry<String, DataSourceProperty> entry : dynamicDataSourceProperties.getDatasource().entrySet()) {
                DataSourceProperty property = entry.getValue();
                Connection connection = DriverManager.getConnection(property.getUrl(), property.getUsername(), property.getPassword());
                connectionMap.put(entry.getKey(), connection);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        log.info("app启动成功！");
    }
}
